package com.livesource.client.webservices.subversion;

import java.util.HashMap;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.jsonp.client.JsonpRequestBuilder;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.livesource.client.InitializeLiveSource;
import com.livesource.client.LiveSourceGlobalVariables;
import com.livesource.client.model.entry.ProjectClass;
import com.livesource.client.model.project.Project;
import com.livesource.client.webservices.GetFileContent;

public class RequestSubversionListFiles {

	private static String url = "http://livesourceagile.com:8080/LiveSourceWebServices/ListSubversionFilesService";

	public static void getJsonpRequest(final Project project) {

		// String username = EncryptText.decrypt(GetCookies.getUsername(project
		// .getProjectID()));
		String username = null;

		// String password =
		// EncryptText.decrypt(GetCookies.getPassword(project.getProjectID()));
		String password = null;

		JsonpRequestBuilder jsonp = new JsonpRequestBuilder();

		jsonp.setTimeout(150000);

		String urlList = url + "?repositoryURL=" + project.getRepositoryURL()
				+ "&username=" + username + "&password=" + password;

		jsonp.requestObject(urlList, new AsyncCallback<JavaScriptObject>() {

			public void onFailure(Throwable throwable) {

				System.out.println("Error: " + throwable);
				Window.alert(throwable.toString());
			}

			public void onSuccess(JavaScriptObject feed) {

				JSONObject objFeed = new JSONObject(feed);

				HashMap<String, ProjectClass> files = new HashMap<String, ProjectClass>();

				for (int i = 0; i < objFeed.size(); i++) {

					JSONObject entry = (JSONObject) objFeed.get(i + "");

					ProjectClass projectEntry = ConvertSubversionToProjectEntry
							.convertJsonp(entry);

					files.put(projectEntry.toString(), projectEntry);

					new GetFileContent(projectEntry,
							LiveSourceGlobalVariables.currentProject);
				}

				LiveSourceGlobalVariables.projectEntries = files;

				InitializeLiveSource.loadPanel();
			}
		});
	}
}
